package com.financing.controller.invest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.financing.common.CONST;
import com.financing.common.DICT;
import com.financing.components.payment.Gateway;
import com.financing.model.Data;
import com.financing.model.invest.Bid;
import com.financing.model.invest.BidDetail;
import com.financing.model.invest.CouponLog;
import com.financing.model.invest.Trade;
import com.financing.model.user.User;
import com.financing.service.invest.BidDetailService;
import com.financing.service.invest.TradeService;
import com.financing.util.DateUtil;
import com.financing.util.Json;
import com.financing.util.Str;
import com.financing.util.XmlHelper;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 交易控制器
 */
public class TradeController extends Controller {
	private static TradeService trade = new TradeService();
	private static BidDetailService bidDetail = new BidDetailService();
    
	/** 
	 * 开始投资
	 */ 
	public void index1() { 
		Ret ret = TradeService.run(getAttr("user"), getParaToInt("bid",0), getParaToInt("tzhb",0), getParaToInt("jxq",0), getParaToInt("tyj",0), getParaToInt("unit",1));
		renderJson(ret.isOk()?Json.ok(ret.getStr("msg")):Json.error(ret.getStr("msg")));
	}

	/**
	 * 获取交易记录列表
	 */
    @Clear
	public void list() {
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String,String> params = Data.flat(getParaMap());
		Page<Trade> p = trade.list(page,size,params);
		p.getList().forEach(n->{
			n.put("fund", User.me.findById(Bid.me.findById(n.getBidId()).getFund()).getRealName());
			n.put("tyj", n.getTyj()>0 ? CouponLog.me.findById(n.getTyj()) : "");
			n.put("tzhb", n.getTzhb()>0 ? CouponLog.me.findById(n.getTzhb()) : "");
			n.put("jxq", n.getJxq()>0 ? CouponLog.me.findById(n.getJxq()) : "");
		});
		
		// 计算总投资金额 
		double total = trade.sumByParams(params);
		
		// 计算总体验金投资金额
		params.put("type", "experi");
		double experi = trade.sumByParams(params);
		
		// 计算总投资人数
		double count = trade.countByParams(params);
		
		renderJson(Json.ok("数据获取成功！", Data.put("count",count, "total",total, "experi",experi, "page", p)));
	} 
	
	/**
	 * 获取我的交易记录列表
	 */
	public void myList() {
		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		String status = getPara("status","holding");
		String createTimeStart = getPara("createTimeStart");
		String createTimeEnd = getPara("createTimeEnd");
		List<Trade> tempList = new ArrayList<Trade>();
		Page<Trade> p = trade.findByUser(page, size, u.getId(), status, createTimeStart, createTimeEnd); 
		// 仅第一页内容需要排序
		if(page==1 && Str.eq("holding", status)){
			trade.findByUser(1, 999, u.getId(), "trading", createTimeStart, createTimeEnd).getList().forEach(n->{
				tempList.add(n);
			});
		}			
		p.getList().forEach(n->{
			tempList.add(n);
		});	
		tempList.forEach(n->{
			n.set("jxq", CouponLog.me.findById(n.getJxq()));
			n.put("contract", "/investment-contract?id="+n.getId()+"&userId="+u.getId());
			if(Str.eq("finish", status)) {
				n.put("actual_repay_time",DateUtil.format(n.getTargetTime(), "yyyy-MM-dd")+" 14:30:00");
			}
		});
		p.getList().clear();
		p.getList().addAll(tempList);
		renderJson(Json.ok("数据获取成功！", Data.put("page", p)));
	} 
	 
	/**
	 * 获取我的交易记录详细
	 */
	public void myDetail() throws Exception {
		User u = getAttr("user");
		int id = getParaToInt("id",0);
		Record r = trade.findDetailByUser(id);
		r.set("jxq", CouponLog.me.findById(r.getInt("jxq")));	
		r.set("repay_type", DICT.repayType(r.getStr("repay_type")));
		if(Str.eq("finish", r.getStr("status"))) {
			r.set("actual_repay_time", DateUtil.format(r.getDate("invest_end_time"), "yyyy-MM-dd")+" 14:30:00");
		}
		 // 获取项目合同信息 
		int bid = r.getInt("id");
		BidDetail bd = bidDetail.findByBid(bid);
		// logger.error("link==="+bd.getContractInfo()+"?token="+getPara("token")+"&userId="+u.getId()+"&id="+bid+"&amount="+r.get("amount"));
		r.set("contract", bd!=null ? "/investment-contract?token="+getPara("token")+"&userId="+u.getId()+"&id="+id+"&amount="+r.get("amount") : "");
		renderJson(Json.ok("数据获取成功！", Data.put("item", r)));
	} 
	
	public void contract() throws Exception {

		int id = getParaToInt("id",0);
		
		// 获取交易记录
		Trade t = Trade.me.findById(id);
		
		 // 获取项目信息 
		Bid b = Bid.me.findById(t.getBidId());
		
		// 获得融资机构
		if( b.isExperi()) {
			b.put("company_name", CONST.COMPANY);
		}else {
			// 获取借款人信息
			User fund = User.me.findById(b.getFund());
			XmlHelper res = Gateway.post("/queryUserInfs.action", 
				Data.put(
					"mchnt_txn_ssn",DateUtil.getTimeStamp(), 
					"mchnt_txn_dt",DateUtil.format(DateUtil.GATEWAY_DEFAULT_FORMAT),
					"user_ids",fund.getCode(),
					"sign","mchnt_cd,mchnt_txn_dt,mchnt_txn_ssn,user_ids,ver"
				)
			);
			if(res.isSuccess()) {
    			b.put("company_name", res.getStr("results/result/cust_nm"));
    			b.put("legal_person", res.getStr("results/result/cust_nm"));
    		}
		}
		renderJson(Json.ok("数据获取成功！", Data.put("bid",b,"trade",t)));
	}
	
	/**
	 * 手动满标触发
	 * @throws Exception 
	 */
	@Clear
	public void full() throws Exception {
		Bid b = Bid.me.findById(getParaToInt("id",0));
		TradeService.full(b);
		renderJson(Json.ok("标的状态修改成功！"));
	}
}
 